<template>
  <div class="comment-post">
    <van-field
      class="post-field"
      v-model.trim="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="请输入留言"
      show-word-limit
    />
    <van-button
      class="post-btn"
      :loading="loading"
      @click="onPost"
      :disabled="!message.length"
    >发布</van-button>
  </div>
</template>

<script>
import { ref } from 'vue'
import { Toast } from 'vant'
import { addComment } from '@/api/comment'
export default {
  name: 'CommentPost',
  props: {
    target: {
      type: [Number, String],
      required: true
    },
    articleId: {
      type: [Number, String],
      default: null
    }
  },
  setup (props, context) {
    const message = ref('')
    const loading = ref(false)
    async function onPost () {
      loading.value = true
      Toast.loading({
        message: '发布中...',
        forbidClick: true,
        duration: 0
      })
      try {
        const { data } = await addComment({
          target: props.target.toString(), // 文章id
          content: message.value, // 内容
          art_id: props.articleId ? props.articleId.toString() : null// 文章id，只在对评论回复时传
        })
        message.value = ''
        context.emit('post-success', data.data)
        Toast.success('发布成功')
      } catch (err) {
        if (err.response && err.response.status === 401) {
          Toast.fail('请先登录')
        } else {
          Toast.fail('操作失败')
        }
      }
      loading.value = false
    }
    return {
      message,
      loading,
      onPost
    }
  }
}
</script>

<style scoped lang="less">
.comment-post {
  display: flex;
  align-items: center;
  padding: 32px 0 32px 32px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    &::before {
      display: none;
    }
  }
}
</style>
